import time
import os
from datetime import datetime
from datetime import timedelta
# 熟练使用上述方法, 按照小标题分类的内容默写
# time


def time_test():
    # 获取当前时间
    print(time.localtime())
    # 改变时区
    os.environ['TZ'] = 'US'
    time.tzset()
    # 时间戳
    print(time.time())

    # 时间格式转换
    # time.struct_time -> str
    t1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(t1)
    # str -> time.struct_time
    t2 = time.strptime("2020-11-17 16:17:17", "%Y-%m-%d %H:%M:%S")
    print(t2)
    # time.struct_time -> tuple
    t3 = tuple(time.localtime())
    print(t3)
    # tuple -> time.struct_time
    t4 = time.struct_time((2020, 10, 11, 22, 12, 22, 1, 233, 0))
    print(t4)
    # time.struct_time -> timestamp
    t5 = time.mktime(time.localtime())
    print(t5)
    # timestamp -> time.struct_time
    t6 = time.localtime(1239123)
    t7 = time.gmtime(1239123)
    print(f"{t6}\n{t7}")

    # 时间运算
    # 只能通过时间格式->元组, 然后创建新元组的方式来新建一个新的时间
    t8 = tuple(time.localtime())
    t9 = (t8[0]+1, t8[1]-2, t8[2], 18, 23, t8[5]+3, 1, 232, 0)
    print(f"{t9}\t{time.strftime('%Y-%m-%d %H:%M:%S',time.struct_time(t9))}")
    # 时间休眠
    time.sleep(0.9)
    return None


# datetime
def datetime_test():
    # 查看时间
    print(datetime.now(tz=None))
    print(datetime.utcnow())
    print(datetime.today())
    # 时间格式的转换
    # datetime.datetime -> str
    d1 = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
    print(d1)
    # str -> datetime.datetime
    d2 = datetime.strptime("2019-09-12 12:22:24", "%Y-%m-%d %H:%M:%S")
    print(d2)
    # datetime.datetime -> timetuple -> tuple
    tt = datetime.now().timetuple()
    d3 = tuple(tt)
    print(d3)
    # tuple -> datetime.datetime
    t = (2020, 5, 12, 23, 32, 22, 3, 213, -1)
    new_t = t[:-3]
    d5 = datetime(*new_t)
    print(d5)
    # datetime.datetime -> timestamp
    d6 = datetime.now().timestamp()
    print(d6)
    # timestamp -> datetime.datetime
    d7 = datetime.fromtimestamp(23478234)
    print(d7)
    # 时间运算
    d8 = datetime(2020, 12, 22, 12, 33, 21, 234323) + timedelta(hours=1)
    print(d8)
    return None


# 封装一个函数get_date(days) , 通过传入的数值days(days=1[-2,3,4,5]), 返回格式化后的时间
def get_date(days):
    # 获取今日日期,是时间格式
    today = datetime.today()
    # 时间运算
    day = today + timedelta(days=days)
    # 换成相应格式的字符串
    date = day.strftime("%Y-%m-%d")
    return date


if __name__ == "__main__":
    time_test()
    datetime_test()
    print(get_date(-1))
    print(get_date(12))
